package com.kinoshita.manager.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.kinoshita.common.result.ResultDO;
import com.kinoshita.common.status.Constant;

import com.kinoshita.manager.api.domain.UserLoginSuccessDO;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 登录成功的处理器
 */
public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {

  private ObjectMapper objectMapper;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) throws IOException, ServletException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    //用户登录成功后生成鉴权信息
    UserLoginSuccessDO userLoginSuccessDO = (UserLoginSuccessDO) authentication.getPrincipal();
    ResultDO resultDO = new ResultDO();
    resultDO.setModel(Constant.DATA_MODEL_KEY, userLoginSuccessDO);
    //回写登录成功后的信息
    response.getWriter().write(objectMapper.writeValueAsString(resultDO));
  }

  public JsonLoginSuccessHandler(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
  }
}
